<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div
        class="search-form divClass"
        v-if="pageData.headerShow"
        style="margin-top: 10px; display: inline-block"
      >
        <div>
          <a-form
            size="small"
            :model="pageData"
            layout="inline"
            style="margin-bottom: 10px"
            ref="formRef"
          >
            <a-form-item
              label="日期"
              field="dateTime"
              :rules="[{ required: true, message: '日期必填' }]"
              :validate-trigger="['change', 'blur']"
            >
              <a-range-picker class="bacClass" v-model="pageData.dateTime" style="width: 247px" />
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div style="float: right; margin-top: 10px">
        <Toolbar
          class="gesture"
          :items="['查询', '全部导出']"
          @select="selectHandler"
          @exportAll="exportAll"
        >
        </Toolbar
      ></div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          :suppressCopyRowsToClipboard="true"
          :suppressRowTransform="true"
          class="ag-theme-alpine"
          :rowData="pageData.tableList"
          :columnDefs="tableColumns"
          :localeText="localeText1"
          @columnResized="onColumnResized"
          @columnMoved="onColumnMoved"
          @columnVisible="onColumnVisible"
          @FilterChanged="FilterChangeds"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
  </pageTabelLayout>
</template>
  <script lang='ts' setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import dayjs from 'dayjs'

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
  showAdd: false,
  sideTitle: '',
  rHeight: 0,
  tableList: [],
  pageLoading: false,
  headerShow: true,
  dateTime: '',
})

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: false,
  suppressRowTransform: true,
}
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}

const tableColumns: any = [
  {
    headerName: '织厂',
    field: 'companyName',
    width: 150,
    rowSpan: (param: any) => {
      if (param.data.companyName) {
        return rowSpan(param)
      }
      return 1
    },
    cellRenderer: (params: any) => {
      if (params.data.companyName) {
        const rowspan: any = rowSpan(params)
        if (rowspan > 1) {
          return `<div style="line-height: ${33 * rowspan}px; height: ${
            33 * rowspan
          }px; background:white;border-bottom:1px solid #dde2eb;">${params.value}</div>`
        } else {
          return `<div>${params.value}</div>`
        }
        33
      }
      return params.value
    },
    cellClassRules: { 'show-cell': true },
  },
  { headerName: '机型', field: 'machineTypeName', width: 150 },
  { headerName: '寸数', field: 'specification', width: 150 },
  { headerName: '机台数', field: 'totalMachineCount', width: 150 },
  {
    headerName: '当日持单量（吨）',
    children: [
      { headerName: '自营单', field: 'toDaySelfOrderWeight', width: 150 },
      { headerName: '加工单', field: 'toDayOutOrderWeight', width: 150 },
      { headerName: '总持单', field: 'toDayTotalHoldings', width: 150 },
    ],
  },
  {
    headerName: '期间开机台数',
    children: [
      { headerName: '自营单', field: 'selfMachineCount', width: 150 },
      { headerName: '加工单', field: 'outMachineCount', width: 150 },
      { headerName: '开机台数中加工单占比', field: 'MachineRatio', width: 150 },
      { headerName: '总开机台数', field: 'Machinetotal', width: 150 },
      { headerName: '总开机率', field: 'TotaliUptim', width: 150 },
    ],
  },
  {
    headerName: '期间产量（吨）',
    children: [
      { headerName: '自营单', field: 'toDaySelfOutput', width: 150 },
      { headerName: '加工单', field: 'toDayOutOutput', width: 150 },
      { headerName: '总产量', field: 'toDayCount', width: 150 },
      { headerName: '加工单比例', field: 'toDayRatio', width: 150 },
    ],
  },
  {
    headerName: '本月累计产量',
    children: [
      { headerName: '自营单', field: 'monthSelfOutput', width: 150 },
      { headerName: '加工单', field: 'monthOutOutput', width: 150 },
      { headerName: '总产量', field: 'monthCount', width: 150 },
      { headerName: '加工单比例', field: 'monthRatio', width: 150 },
    ],
  },
]

//分页
const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}

//查询
const formRef = ref<FormInstance>()
function doRefresh() {
  formRef.value?.validate().then((err: any) => {
    if (!err) {
      pageData.pageLoading = true
      updateGridState01()
      get({
        url: '/planSingle/ClothScan/buildDailyOutput',
        data:{
          startDate:pageData.dateTime ? pageData.dateTime[0] : '', 
          endDate:pageData.dateTime ? pageData.dateTime[1] : '', 
        }
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            data.forEach((o: any) => {
              o.toDayTotalHoldings = parseFloat(
                (o.toDaySelfOrderWeight + o.toDayOutOrderWeight).toFixed(2)
              )
              o.monthCount = parseFloat((o.monthSelfOutput + o.monthOutOutput).toFixed(2)) //本月总产量
              o.monthRatio = ((o.monthOutOutput / o.monthCount) * 100).toFixed(2) + '%' //本月加工单比例
              o.toDayCount = parseFloat((o.toDaySelfOutput + o.toDayOutOutput).toFixed(2)) //当日总产量
              o.toDayRatio = ((o.toDayOutOutput / o.toDayCount) * 100).toFixed(2) + '%' //当日加工单比例
              o.Machinetotal = o.selfMachineCount + o.outMachineCount //当日总开机台数
              o.MachineRatio = ((o.outMachineCount / o.Machinetotal) * 100).toFixed(2) + '%' //期间开机台数中加工单占比
              o.TotaliUptim = ((o.Machinetotal / o.totalMachineCount) * 100).toFixed(2) + '%' //当日总开机率
            })
            pageData.tableList = data
            gridOption.value.setRowData(data)
            createRowCount(pageData.tableList)
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
  })
}

const selectHandler = () => {
  page.value = 1
  doRefresh()
}

const exportAll = () => {
  let head = `<thead>
                <tr>
                  <th rowspan="2">织厂</th>
                  <th rowspan="2">机型</th>
                  <th rowspan="2">寸数</th>
                  <th rowspan="2">机台数</th><
                  <th colspan="3">当日持单量（吨）</th>
                  <th colspan="5">期间开机台数</th>
                  <th colspan="4">期间产量（吨）</th>
                  <th colspan="4">本月累计产量</th>
                </tr>
                <tr>
                  <th>自营单</th>
                  <th>加工单</th>
                  <th>总持单</th>
                  <th>自营单</th>
                  <th>加工单</th>
                  <th>开机台数中加工单占比</th>
                  <th>总开机台数</th>
                  <th>总开机率</th>
                  <th>自营单</th>
                  <th>加工单</th>
                  <th>总产量</th>
                  <th>加工单比例</th>
                  <th>自营单</th>
                  <th>加工单</th>
                  <th>总产量</th>
                  <th>加工单比例</th>'
                </tr>
              </thead>
  `
  let body = ''
  let data = [...pageData.tableList, ...rowCount]
  data.forEach(function (o: any) {
    body += '<tr><td>' + (o['companyName'] == undefined ? '' : o['companyName']) + '</td>'
    body += '<td>' + o['machineTypeName'] + '</td>'
    body += '<td>' + o['specification'] + '</td>'
    body += '<td>' + o['totalMachineCount'] + '</td>'
    body += '<td>' + o['toDaySelfOrderWeight'] + '</td>'
    body += '<td>' + o['toDayOutOrderWeight'] + '</td>'
    body += '<td>' + o['toDayTotalHoldings'] + '</td>'
    body += '<td>' + o['selfMachineCount'] + '</td>'
    body += '<td>' + o['outMachineCount'] + '</td>'
    body += '<td>' + o['MachineRatio'] + '</td>'
    body += '<td>' + o['Machinetotal'] + '</td>'
    body += '<td>' + o['TotaliUptim'] + '</td>'
    body += '<td>' + o['toDaySelfOutput'] + '</td>'
    body += '<td>' + o['toDayOutOutput'] + '</td>'
    body += '<td>' + o['toDayCount'] + '</td>'
    body += '<td>' + o['toDayRatio'] + '</td>'
    body += '<td>' + o['monthSelfOutput'] + '</td>'
    body += '<td>' + o['monthOutOutput'] + '</td>'
    body += '<td>' + o['monthCount'] + '</td>'
    body += '<td>' + o['monthRatio'] + '</td></tr>'
  })
  tableToXlsx(head, '织造产量日报表', body)
}
function tableToXlsx(head: any, filename: any, body: any) {
  const uri = 'data:application/vnd.ms-excel;base64,',
    template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

  const a = document.createElement('a')
  a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
  a.download = filename
  a.click()
  document.removeChild(a)
}

const rowSpan = (param: any) => {
  const arr = ['companyName']
  if (arr.indexOf(param.column.colId) !== -1) {
    // 需要校验的字段
    const data = arr.slice(0, arr.indexOf(param.column.colId) + 1)
    // 每一条第一次出现时对应的索引
    const first = pageData.tableList.findIndex((item: any) => {
      return data.every((v) => item[v] === param.data[v])
    })
    if (param.node.childIndex === first) {
      // 同一条出现的条数
      const rowspan = pageData.tableList.filter((item: any) => {
        return data.every((v) => item[v] === param.data[v])
      }).length
      return rowspan
    } else {
      return 1
    }
  }
}

// 底部汇总
let rowCount: any = []
function createRowCount(data: any) {
  let nowRows: any = []
  const machineTypeTotals = {}
  data = data.filter((o: any) => o.machineTypeName != '小计')
  data.forEach((o: any) => {
    if (!machineTypeTotals[o.machineTypeName]) {
      machineTypeTotals[o.machineTypeName] = {
        totalMachineCount: 0,
        toDayOutOrderWeight: 0,
        toDaySelfOrderWeight: 0,
        toDayTotalHoldings: 0,
        selfMachineCount: 0,
        outMachineCount: 0,
        Machinetotal: 0,
        MachineRatio: 0,
        TotaliUptim: 0,
        toDayOutOutput: 0,
        toDaySelfOutput: 0,
        toDayCount: 0,
        monthOutOutput: 0,
        monthCount: 0,
        toDayRatio: 0,
        monthRatio: 0,
        monthSelfOutput: 0,
      }
    }
    // 累加每个字段的值
    machineTypeTotals[o.machineTypeName].totalMachineCount += o.totalMachineCount
    machineTypeTotals[o.machineTypeName].toDayOutOrderWeight += o.toDayOutOrderWeight
    machineTypeTotals[o.machineTypeName].toDaySelfOrderWeight += o.toDaySelfOrderWeight
    machineTypeTotals[o.machineTypeName].toDayTotalHoldings += o.toDayTotalHoldings
    machineTypeTotals[o.machineTypeName].selfMachineCount += o.selfMachineCount
    machineTypeTotals[o.machineTypeName].outMachineCount += o.outMachineCount
    machineTypeTotals[o.machineTypeName].Machinetotal += o.Machinetotal
    machineTypeTotals[o.machineTypeName].MachineRatio =
      (
        (machineTypeTotals[o.machineTypeName].outMachineCount /
          machineTypeTotals[o.machineTypeName].Machinetotal) *
        100
      ).toFixed(2) + '%'
    machineTypeTotals[o.machineTypeName].TotaliUptim =
      (
        (machineTypeTotals[o.machineTypeName].Machinetotal /
          machineTypeTotals[o.machineTypeName].totalMachineCount) *
        100
      ).toFixed(2) + '%'
    machineTypeTotals[o.machineTypeName].toDayOutOutput += o.toDayOutOutput
    machineTypeTotals[o.machineTypeName].toDaySelfOutput += o.toDaySelfOutput
    machineTypeTotals[o.machineTypeName].toDaySelfOutput += o.toDaySelfOutput
    machineTypeTotals[o.machineTypeName].toDayCount += o.toDayCount
    machineTypeTotals[o.machineTypeName].monthOutOutput += o.monthOutOutput
    machineTypeTotals[o.machineTypeName].monthCount += o.monthCount
    machineTypeTotals[o.machineTypeName].toDayRatio =
      (
        (machineTypeTotals[o.machineTypeName].toDayOutOutput /
          machineTypeTotals[o.machineTypeName].toDayCount) *
        100
      ).toFixed(2) + '%'
    machineTypeTotals[o.machineTypeName].monthRatio =
      (
        (machineTypeTotals[o.machineTypeName].monthOutOutput /
          machineTypeTotals[o.machineTypeName].monthCount) *
        100
      ).toFixed(2) + '%'
    machineTypeTotals[o.machineTypeName].monthSelfOutput += o.monthSelfOutput
  })

  // 将 machineTypeTotals 转换为 nowRows 数组
  Object.keys(machineTypeTotals).forEach((machineTypeName) => {
    const {
      totalMachineCount,
      toDayOutOrderWeight,
      toDaySelfOrderWeight,
      toDayTotalHoldings,
      selfMachineCount,
      outMachineCount,
      Machinetotal,
      MachineRatio,
      TotaliUptim,
      toDayOutOutput,
      toDaySelfOutput,
      toDayCount,
      monthOutOutput,
      monthCount,
      toDayRatio,
      monthRatio,
      monthSelfOutput,
    } = machineTypeTotals[machineTypeName]

    nowRows.push({
      companyName: '合计',
      machineTypeName: machineTypeName,
      totalMachineCount,
      toDayOutOrderWeight,
      toDaySelfOrderWeight,
      toDayTotalHoldings,
      selfMachineCount,
      outMachineCount,
      Machinetotal,
      MachineRatio,
      TotaliUptim,
      toDayOutOutput,
      toDaySelfOutput,
      toDayCount,
      monthOutOutput,
      monthCount,
      toDayRatio,
      monthRatio,
      monthSelfOutput,
    })
  })

  let sum1 = 0
  let sum2 = 0
  let sum3 = 0
  let sum4 = 0
  let sum5 = 0
  let sum6 = 0
  let sum7 = 0
  let sum8 = 0
  let sum9 = 0
  let sum10 = 0
  let sum11 = 0
  let sum12 = 0
  let sum13 = 0
  let sum14 = 0
  let sum15 = 0
  let sum16 = 0
  let sum17 = 0
  for (var i = 0; i < data.length; i++) {
    sum1 = sum1 + data[i].totalMachineCount
    sum2 = sum2 + data[i].toDayOutOrderWeight
    sum3 = sum3 + data[i].toDaySelfOrderWeight
    sum4 = sum4 + data[i].toDayTotalHoldings
    sum5 = sum5 + data[i].selfMachineCount
    sum6 = sum6 + data[i].outMachineCount
    sum7 = sum7 + data[i].Machinetotal
    sum8 = (sum6 / sum7) * 100
    sum9 = (sum7 / sum1) * 100
    sum10 = sum10 + data[i].toDayOutOutput
    sum11 = sum11 + data[i].toDaySelfOutput
    sum12 = sum12 + data[i].toDayCount
    sum13 = sum13 + data[i].monthOutOutput
    sum14 = sum14 + data[i].monthCount
    sum15 = (sum10 / sum12) * 100
    sum16 = (sum13 / sum14) * 100
    sum17 = sum17 + data[i].monthSelfOutput
  }
  var nowRows2 = [
    {
      machineTypeName: '总合计',
      totalMachineCount: sum1,
      toDayOutOrderWeight: sum2.toFixed(2),
      toDaySelfOrderWeight: sum3.toFixed(2),
      toDayTotalHoldings: sum4.toFixed(2),
      selfMachineCount: sum5,
      outMachineCount: sum6,
      Machinetotal: sum7,
      MachineRatio: sum8.toFixed(2) + '%',
      TotaliUptim: sum9.toFixed(2) + '%',
      toDayOutOutput: sum10.toFixed(2),
      toDaySelfOutput: sum11.toFixed(2),
      toDayCount: sum12.toFixed(2),
      monthOutOutput: sum13.toFixed(2),
      monthCount: sum14.toFixed(2),
      toDayRatio: sum15.toFixed(2) + '%',
      monthRatio: sum16.toFixed(2) + '%',
      monthSelfOutput: sum17.toFixed(2),
    },
  ]
  rowCount = [...nowRows, ...nowRows2]
  // 设置底部合计行数据
  gridOption.value.setPinnedBottomRowData(rowCount)
}

onMounted(() => {
  pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight
  }
  pageData.dateTime = [dayjs().format('YYYY-MM-DD'),dayjs().format('YYYY-MM-DD')]
  doRefresh()
})

const FilterChangeds = (params: any) => {
  let data: any = {
    list: [],
  }
  params.api.forEachNodeAfterFilter((row: any) => {
    data.list.push(row.data)
  })
  createRowCount(data.list)
}

const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
  saveOrUpdateGridState01('productionWeaveDaily-1', gridOption, colState, tableColumns)
const onColumnMoved = () => {
  saveGridState01()
}
const onColumnResized = () => {
  saveGridState01()
}
const onColumnVisible = () => {
  saveGridState01()
}
</script>
    <style scoped>
:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}
:deep(.show-cell) {
  display: inline-block;
  vertical-align: middle;
}
</style>
    